/**
 * 对象池 - 用于管理子弹、敌机等频繁创建销毁的对象
 */
export class ObjectPool<T> {
  private available: T[] = [];
  private createFn: () => T;
  private resetFn?: (item: T) => void;
  private onAcquire?: (item: T) => void;

  constructor(
    createFn: () => T,
    resetFn?: (item: T) => void,
    onAcquire?: (item: T) => void
  ) {
    this.createFn = createFn;
    this.resetFn = resetFn;
    this.onAcquire = onAcquire;
  }

  /**
   * 获取一个对象实例
   */
  acquire(): T {
    const item = this.available.pop() ?? this.createFn();
    this.onAcquire?.(item);
    return item;
  }

  /**
   * 释放对象回池中
   */
  release(item: T): void {
    this.resetFn?.(item);
    this.available.push(item);
  }

  /**
   * 获取池中可用对象数量
   */
  getAvailableCount(): number {
    return this.available.length;
  }

  /**
   * 预填充对象池
   */
  preFill(count: number): void {
    for (let i = 0; i < count; i++) {
      this.available.push(this.createFn());
    }
  }
}